import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';

class AppUpdate {
  final String versionUrl = 'http://app.mkkxy.com/kxy-version.json';
  Future checkUpdate(BuildContext context, {bool withLatestVersionTip = true}) async {
    if (Platform.isAndroid) {
      await FlutterXUpdate.init(
        // 是否输出日志
        debug: true,
        // 是否使用post请求
        isPost: false,
        // post请求是否是上传json
        isPostJson: false,
        // 是否开启自动模式
        isWifiOnly: false,
        // 是否开启自动模式
        isAutoMode: false,
        // 需要设置的公共参数
        supportSilentInstall: false,
        // 在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
        enableRetry: false,
      );
      FlutterXUpdate.setErrorHandler(onUpdateError: (Map<String, dynamic> message) async {
        if (message['code'] != 2004) {
          Fluttertoast.showToast(msg: message['message']);
        }

        if (message['code'] == 2004 && withLatestVersionTip) {
          Fluttertoast.showToast(msg: message['message']);
        }
      });
      await FlutterXUpdate.checkUpdate(url: versionUrl);
    } else {
      var packageInfo = await PackageInfo.fromPlatform();
      int buildNumber = int.parse(packageInfo.buildNumber);

      Dio dio = new Dio();
      var res = await dio.get(versionUrl);
      if (buildNumber < res.data['VersionCode']) {
        showIOSUpdateDialog(res.data['VersionName'], context);
      } else {
        if (withLatestVersionTip) {
          Fluttertoast.showToast(msg: '已经是最新版本');
        }
      }
    }
  }

  void showIOSUpdateDialog(String versionName, BuildContext context) {
    showDialog(
      context: context,
      builder: (cxt) {
        return CupertinoAlertDialog(
          title: Text('更新提醒'),
          content: Text('检测到新版本 v$versionName'),
          actions: [
            FlatButton(
              textColor: Colors.black54,
              onPressed: () => Navigator.pop(context),
              child: Text('下次再说'),
            ),
            FlatButton(
              textColor: Theme.of(context).primaryColor,
              onPressed: () {
                Navigator.pop(context);
                launch('https://apps.apple.com/cn/app/%E7%9F%BF%E6%A0%A1%E4%BA%91/id1472197247');
              },
              child: Text('立即更新'),
            ),
          ],
        );
      },
    );
  }
}
